package com.wash.shoes.domain.jd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lop.open.api.sdk.DefaultDomainApiClient;
import com.lop.open.api.sdk.LopException;
import com.lop.open.api.sdk.domain.ECAP.CommonCreateOrderApi.commonCheckPreCreateOrderV1.CommonCreateOrderRequest;
import com.lop.open.api.sdk.domain.ECAP.CommonCreateOrderApi.commonCheckPreCreateOrderV1.CommonProductInfo;
import com.lop.open.api.sdk.domain.ECAP.CommonCreateOrderApi.commonCheckPreCreateOrderV1.Contact;
import com.lop.open.api.sdk.domain.ECAP.CommonCreateOrderApi.preGetWaybillCodes.PreGetWaybillCodesRequest;
import com.lop.open.api.sdk.domain.ECAP.CommonModifyCancelOrderApi.commonCancelOrderV1.CommonOrderCancelRequest;
import com.lop.open.api.sdk.domain.ECAP.CommonQueryOrderApi.commonGetOrderStatusV1.CommonOrderStatusRequest;
import com.lop.open.api.sdk.domain.ECAP.CommonQueryOrderApi.commonGetOrderTraceV1.CommonOrderTraceRequest;
import com.lop.open.api.sdk.plugin.LopPlugin;
import com.lop.open.api.sdk.plugin.factory.OAuth2PluginFactory;
import com.lop.open.api.sdk.request.ECAP.*;
import com.lop.open.api.sdk.response.ECAP.*;
import com.ruoyi.common.core.domain.R;
import com.wash.shoes.common.property.JdProperty;
import com.wash.shoes.domain.dto.MtUserAddress;
import com.wash.shoes.entity.JdCallRecordPo;
import com.wash.shoes.entity.OrderPo;
import com.wash.shoes.entity.OrderTransportPo;
import com.wash.shoes.exception.WashException;
import com.wash.shoes.service.JdCallRecordService;
import com.wash.shoes.service.OrderService;
import com.wash.shoes.service.OrderTransportService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Objects;

/**
 * @author lijianguo
 * @Date 07/12/2024 11:13
 * jd的信息
 **/
@Log4j2
@Service
public class JdOrderService {

    @Autowired
    JdCallRecordService jdCallRecordService;

    @Autowired
    OrderService orderService;

    @Autowired
    JdProperty jdProperty;

    @Autowired
    OrderTransportService orderTransportService;

    @PostConstruct
    public void init() {

        //  preCheckAddress("西藏军安卫士花园","四川省成都市中和职业中学");


    }

    /**
     * 取消jd的订单信息
     *
     * @param wayBillCode 运输号
     */
    public void cancelJdOrder(String wayBillCode) {

        OrderTransportPo orderTransportPo = orderTransportService.getByWayBillCode(wayBillCode);

        OrderPo orderPo = orderService.getById(orderTransportPo.getOrderId());
        EcapV1OrdersCancelLopRequest cancelLopRequest = new EcapV1OrdersCancelLopRequest();
        DefaultDomainApiClient client = new DefaultDomainApiClient(jdProperty.getUrl(), 5000, 15000);
        LopPlugin lopPlugin = OAuth2PluginFactory.produceLopPlugin(jdProperty.getAppKey(), jdProperty.getAppSecret(), jdProperty.getAccessToken());
        cancelLopRequest.addLopPlugin(lopPlugin);

        CommonOrderCancelRequest commonOrderCancelRequest = new CommonOrderCancelRequest();
        commonOrderCancelRequest.setOrderOrigin(Integer.parseInt(orderTransportPo.getOrderOrigin()));
        commonOrderCancelRequest.setCancelReason("用户取消");
        // 取消原因编码；枚举值：1-用户发起取消；2-超时未支付
        commonOrderCancelRequest.setCancelReasonCode("1");
        commonOrderCancelRequest.setCustomerCode(jdProperty.getCustomerCode());
        commonOrderCancelRequest.setWaybillCode(wayBillCode);
        cancelLopRequest.setRequest(commonOrderCancelRequest);
        try {
            EcapV1OrdersCancelLopResponse response = client.execute(cancelLopRequest);
            log.info("EcapV1OrdersCancelLopResponse is request:[{}]  response:[{}]", JSONObject.toJSONString(commonOrderCancelRequest), JSONObject.toJSONString(response));
            // 调用的记录
            JdCallRecordPo jdCallRecordPo = new JdCallRecordPo();
            jdCallRecordPo.setWayBillCode(wayBillCode);
            jdCallRecordPo.setOrderId(orderPo.getId());
            jdCallRecordPo.setOrderNo(orderPo.getOrderNo());
            jdCallRecordPo.setRequestInfo(JSONObject.toJSONString(commonOrderCancelRequest));
            jdCallRecordPo.setRespondInfo(JSONObject.toJSONString(response));
            jdCallRecordPo.setRequestId(response.getResult().getRequestId());
            jdCallRecordService.save(jdCallRecordPo);
            // 取消订单
            orderTransportPo.setStatus("690");
            orderTransportService.updateById(orderTransportPo);
        } catch (LopException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 京东物流状态判断
     *
     * @param orderTransportPo
     * @return
     */
    public String jdLogisticsStatus(OrderTransportPo orderTransportPo) {
        EcapV1OrdersStatusGetLopResponse response;
        try {
            // 构造请求
            EcapV1OrdersStatusGetLopRequest request = new EcapV1OrdersStatusGetLopRequest();
            CommonOrderStatusRequest commonRequest = new CommonOrderStatusRequest();
            commonRequest.setWaybillCode(orderTransportPo.getWayBillCode());
            commonRequest.setOrderOrigin(Integer.parseInt(orderTransportPo.getOrderOrigin()));
            commonRequest.setCustomerCode(jdProperty.getCustomerCode());
            request.setRequest(commonRequest);
            // 初始化京东API客户端
            DefaultDomainApiClient client = new DefaultDomainApiClient(jdProperty.getUrl(), 5000, 15000);
            LopPlugin lopPlugin = OAuth2PluginFactory.produceLopPlugin(jdProperty.getAppKey(), jdProperty.getAppSecret(), jdProperty.getAccessToken());
            request.addLopPlugin(lopPlugin);
            // 执行请求
            response = client.execute(request);
            // 日志记录请求和响应
            log.info("商家取消订单查询物流状态请求: {}", JSONObject.toJSONString(request));
            log.info("商家取消订单查询物流状态返回: {}", JSONObject.toJSONString(response));
            // 结果检查
            if (Objects.isNull(response) || Objects.isNull(response.getResult()) || Objects.isNull(response.getResult().getData())) {
                log.warn("查询京东物流状态返回结果为空，WayBillCode: {}", orderTransportPo.getWayBillCode());
                return "";
            }
            // 返回物流状态
            return response.getResult().getData().getStatus();

        } catch (LopException e) {
            log.error("查询京东物流状态时发生异常, WayBillCode: {}, 原因: {}", orderTransportPo.getWayBillCode(), e.getMessage(), e);
            throw new WashException("查询京东物流状态失败: " + e.getMessage(), e);
        }
    }

    /**
     * 获取物流的状态
     */
    public EcapV1OrdersTraceQueryLopResponse getTransInfo(String wayBillCode) {

        OrderTransportPo orderTransportPo = orderTransportService.getByWayBillCode(wayBillCode);

        EcapV1OrdersTraceQueryLopRequest request = new EcapV1OrdersTraceQueryLopRequest();
        CommonOrderTraceRequest commonRequest = new CommonOrderTraceRequest();
        request.setCommonOrderTraceRequest(commonRequest);
        commonRequest.setWaybillCode(wayBillCode);
        commonRequest.setOrderOrigin(Integer.parseInt(orderTransportPo.getOrderOrigin()));
        commonRequest.setCustomerCode(jdProperty.getCustomerCode());

        DefaultDomainApiClient client = new DefaultDomainApiClient(jdProperty.getUrl(), 5000, 15000);
        LopPlugin lopPlugin = OAuth2PluginFactory.produceLopPlugin(jdProperty.getAppKey(), jdProperty.getAppSecret(), jdProperty.getAccessToken());
        request.addLopPlugin(lopPlugin);

        try {
            EcapV1OrdersTraceQueryLopResponse response = client.execute(request);
            log.info("查询运单全程跟踪  request {} ", JSONObject.toJSONString(request));
            log.info("查询运单全程跟踪  response {} ", JSONObject.toJSONString(response));
            return response;
        } catch (LopException e) {
            log.error(e);
            return null;
        }
    }

    /**
     * 检查支付的地址 /ecap/v1/orders/precheck
     */
    public String preCheckAddress(String sendAddress, String receiverAddress) {
        Integer orderOrigin = 2;
        // 生成jd的物流单号
        DefaultDomainApiClient client = new DefaultDomainApiClient(jdProperty.getUrl(), 5000, 15000);
        //入参对象（请记得更换为自己要使用的接口入参对象）
        EcapV1OrdersPrecheckLopRequest request = new EcapV1OrdersPrecheckLopRequest();
        //设置入参（请记得更换为自己要使用的接口入参）
        Contact senderContact = new Contact();
        senderContact.setFullAddress(sendAddress);
        Contact receiverContact = new Contact();
        receiverContact.setFullAddress(receiverAddress);
        CommonCreateOrderRequest requestDTO = new CommonCreateOrderRequest();
        requestDTO.setOrderOrigin(1);
        requestDTO.setCustomerCode(jdProperty.getCustomerCode());
        CommonProductInfo productInfo = new CommonProductInfo();
        productInfo.setProductCode("ed-m-0001");
        requestDTO.setProductsReq(productInfo);
        requestDTO.setReceiverContact(receiverContact);
        requestDTO.setSenderContact(senderContact);
        request.setRequest(requestDTO);
        //设置插件，必须的操作，不同类型的应用入参不同，请看入参注释，公共参数按顺序分别为AppKey、AppSecret、AccessToken
        //使用开放平台ISV/自研商家应用调用接口
        LopPlugin lopPlugin = OAuth2PluginFactory.produceLopPlugin(jdProperty.getAppKey(), jdProperty.getAppSecret(), jdProperty.getAccessToken());
        request.addLopPlugin(lopPlugin);
        EcapV1OrdersPrecheckLopResponse response = null;
        try {
            response = client.execute(request);
            log.info("request {} ", JSONObject.toJSONString(request));
            if (response.getResult().getCode() == 0) {
                return "success";
            } else {
                return response.getResult().getMsg();
            }
        } catch (LopException e) {
            return null;
        }
    }

}
